package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserCilent;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuuthServiceImpl implements UserAuuthService {
    @Autowired
    private UserCilent userCilent;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void login(String username, String password, HttpServletResponse response) {
        UserDTO userDTO = null;

        try {
            userDTO = this.userCilent.queryUserByPhoneAndPassword(username, password);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.getMessage());
        }
        UserDetail userDetail = BeanHelper.copyProperties(userDTO, UserDetail.class);
        String token = jwtUtils.createJwt(userDetail);
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);

        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }


    @Override
    public void logout(HttpServletResponse response,HttpServletRequest request) {
        try {
            //获取cookie信息,从redis删除
            String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(token);
            String username = payload.getUserDetail().getUsername();
            String key = JwtConstants.KEY_PREFIX + username;
            System.out.println("key?>???:"+key);
            redisTemplate.delete(key);
        } catch (Exception e) {
        }

        //创建Cookie
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, "");
        //设置cookie绑定的域名
        cookie.setDomain(JwtConstants.DOMAIN);
        //立即删除
        cookie.setMaxAge(0);
        //绑定当前域名下的路径
        cookie.setPath("/");
        //拒绝脚本操作和访问
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
